import { useEffect, useState } from "react";
import type { FormInstance, TableColumnsType } from "antd";
import type { TableProps } from "antd";
import { Button, Flex, Form, Input, InputNumber, Popconfirm, Select, Table, Typography } from "antd";
import VideoPreview from "@/components/video-preview";
import type { Values } from "../types";

interface EditFormProps {
  initialValues?: Values;
  onFormInstanceReady: (instance: FormInstance<Values>) => void;
  onConfirm: () => void;
  onCancel: () => void;
}

interface DataType {
  key: string;
  id: number;
  frame: string;
  framePreview: string;
  startTime: number;
  endTime: number;
  words: string;
}

interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
  editing: boolean;
  dataIndex: string;
  title: any;
  inputType: "number" | "text";
  record: DataType;
  index: number;
}

const dataSource: DataType[] = [
  {
    key: "1",
    id: 1,
    frame: "片段1",
    framePreview: "1234567890",
    startTime: 1,
    endTime: 10,
    words: "1234567890",
  },
  {
    key: "2",
    id: 1,
    frame: "片段1",
    framePreview: "1234567890",
    startTime: 1,
    endTime: 10,
    words: "1234567890",
  },
  {
    key: "3",
    id: 1,
    frame: "片段1",
    framePreview: "1234567890",
    startTime: 1,
    endTime: 10,
    words: "1234567890",
  },
  {
    key: "4",
    id: 1,
    frame: "片段1",
    framePreview: "1234567890",
    startTime: 1,
    endTime: 10,
    words: "1234567890",
  },
  {
    key: "5",
    id: 1,
    frame: "片段1",
    framePreview: "1234567890",
    startTime: 1,
    endTime: 10,
    words: "1234567890",
  },
  {
    key: "6",
    id: 1,
    frame: "片段1",
    framePreview: "1234567890",
    startTime: 1,
    endTime: 10,
    words: "1234567890",
  },
];

const EditableCell: React.FC<React.PropsWithChildren<EditableCellProps>> = ({
  editing,
  dataIndex,
  title,
  inputType,
  // record,
  // index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === "number" ? <InputNumber /> : <Input />;

  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};
export default function EditForm({ onFormInstanceReady, onConfirm, onCancel }: EditFormProps) {
  const [form] = Form.useForm();
  const [tableForm] = Form.useForm();
  const [data, setData] = useState<DataType[]>(dataSource);
  const [isEdit, setIsEdit] = useState(false);

  const [editingKey, setEditingKey] = useState("");

  const isEditing = (record: DataType) => record.key === editingKey;

  const edit = (record: Partial<DataType> & { key: React.Key }) => {
    form.setFieldsValue({ name: "", age: "", address: "", ...record });
    setEditingKey(record.key);
  };

  const cancel = () => {
    setEditingKey("");
  };

  const save = async (key: React.Key) => {
    try {
      const row = (await form.validateFields()) as DataType;

      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        setData(newData);
        setEditingKey("");
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey("");
      }
    } catch (errInfo) {
      console.log("Validate Failed:", errInfo);
    }
  };

  const columns: TableColumnsType<DataType> = [
    {
      title: "镜头描述",
      dataIndex: "frame",
      key: "frame",
      width: 100,
    },
    {
      title: "开始秒",
      dataIndex: "startTime",
      key: "startTime",
    },
    {
      title: "结束秒",
      dataIndex: "endTime",
      key: "endTime",
    },
    {
      title: "景别",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "运镜",
      dataIndex: "address",
      key: "address",
    },
    {
      title: "拍摄内容",
      dataIndex: "words",
      key: "words",
    },
    {
      title: "字幕",
      dataIndex: "words",
      key: "words",
    },
    {
      title: "口播",
      dataIndex: "words",
      key: "words",
    },
    {
      title: "操作",
      dataIndex: "operation",
      fixed: "right",
      width: 100,
      render: (_: any, record: DataType) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link onClick={() => save(record.key)} style={{ marginInlineEnd: 8 }}>
              保存
            </Typography.Link>
            <Popconfirm title="确定取消编辑吗?" onConfirm={cancel}>
              <a>取消</a>
            </Popconfirm>
          </span>
        ) : (
          <Typography.Link disabled={editingKey !== ""} onClick={() => edit(record)}>
            编辑
          </Typography.Link>
        );
      },
    },
  ];

  const mergedColumns: TableProps<DataType>["columns"] = columns.map((col: any) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: DataType) => ({
        record,
        inputType: col.dataIndex === "age" ? "number" : "text",
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  useEffect(() => {
    onFormInstanceReady(form);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <Flex vertical gap={16}>
      <Flex>
        <VideoPreview
          src={"https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4"}
          poster="https://picsum.photos/200/300"
          width={360}
          height={300}
        ></VideoPreview>
        <Form
          form={form}
          layout="horizontal"
          className="ml-4 flex-1"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
        >
          <Form.Item label="视频ID" name="category" className="mb-2">
            <Input readOnly variant="borderless" />
          </Form.Item>
          <Form.Item label="视频地址" name="videoUrl" className="mb-2">
            <Input readOnly variant="borderless" />
          </Form.Item>
          <Form.Item label="视频标题" name="title" className="mb-2">
            <Input />
          </Form.Item>
          <Form.Item label="内容类目" name="contentCategory" className="mb-2">
            <Select />
          </Form.Item>
          <Form.Item label="二级类目" name="secondaryCategory" className="mb-2">
            <Select />
          </Form.Item>
          <Form.Item label="用户端" name="status" className="mb-2">
            <Select />
          </Form.Item>
          <Form.Item label="备注" name="remark" className="mb-2">
            <Input.TextArea rows={2} />
          </Form.Item>
        </Form>
      </Flex>
      <Flex vertical gap={16} className="overflow-x-auto">
        <Flex justify="space-between">
          <h1 className="text-lg font-bold">脚本结构</h1>
          <Flex gap={8}>
            <Button type="primary" ghost>
              重新分析
            </Button>
            <Button type="primary" onClick={() => setIsEdit(!isEdit)}>
              编辑
            </Button>
          </Flex>
        </Flex>
        <Flex className="max-h-[240px] overflow-y-scroll">
          <Form form={tableForm} component={false}>
            <Table
              dataSource={dataSource}
              columns={mergedColumns}
              pagination={false}
              components={{
                body: {
                  cell: EditableCell,
                },
              }}
              scroll={{ x: 800 }}
            />
          </Form>
        </Flex>
      </Flex>
      <Flex justify="center" gap={16}>
        <Button type="primary" ghost onClick={() => onCancel()}>
          取消
        </Button>
        <Button type="primary" onClick={() => onConfirm()}>
          确定
        </Button>
      </Flex>
    </Flex>
  );
}
